<template>
  <div class="user-container">
    <bread second="用户管理" third="用户列表"></bread>
    <el-card class="box-card">
      <div style="margin-top:15px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="userObj.query"
              class="input-with-select"
              clearable
              @clear="getUsers"
            >
              <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
            </el-input>
          </el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple-light"></div>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="tableData" border style="width: 100%;margin-top:10px">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100px"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="telephone" label="状态" width="100px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="get(scope.row)">
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i>
            </el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" size="mini" @click="setting(scope.row)">
                <i class="el-icon-setting"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="userObj.pagenum"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="userObj.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加用户模板 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <!-- <span style="color:red;margin-top:10px">*</span> -->
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑模板 -->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisible2">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisible3">
      <el-form :model="form">
        <el-form-item label="当前的用户：" :label-width="formLabelWidth">
          <span>{{ sname }}</span>
          <!-- <el-input v-model="form.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="当前的角色：" :label-width="formLabelWidth">
          <span>{{ srole }}</span>
        </el-form-item>
        <el-form-item label="分配新角色：" :label-width="formLabelWidth">
          <el-select v-model="form.rid" placeholder="请选择">
            <el-option
              :label="item.roleName"
              :value="item.id"
              v-for="(item, index) in rolemsg"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="fenpeiRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/* eslint-disable */
import {
  users_api,
  addUser_api,
  changeUserState_api,
  delUser_api,
  editUser_api,
  getUserRolenam_api,
  fenpeiRole_api,
  getroleid_api
} from '@/api/index.js'

export default {
  data() {
    return {
      ruleForm: {
        name: '',
        pass: '',
        eml: '',
        tel: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11个字符', trigger: 'blur' }
        ]
      },
      tableData: [],
      userObj: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: null,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: '',
        rid: '',
      },
      formLabelWidth: '120px',
      sname: '',
      srole: '',
      uid: '',
      rolemsg: null
    }
  },
  created() {
    // 获取用户列表
    this.getUsers()
  },
  methods: {
    // 获取用户列表
    async getUsers() {
      const { data: res } = await users_api(this.userObj)
      this.tableData = res.data.users
      this.total = res.data.total
    },
    // 添加用户列表
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await addUser_api(this.form)
          if (res.meta.status === 201) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            this.dialogFormVisible = !this.dialogFormVisible
            this.getUsers()
            //清空表单数据
            this.$refs.ruleForm.resetFields();
          }
        }
      })
    },
    // 编辑用户
    get(row) {
      this.dialogFormVisible2 = true
      this.form.username = row.username
      this.form.email = row.email
      this.form.mobile = row.mobile
      this.form.id = row.id
    },
    editUserInfo() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) {
          return
        } else {
          const { data: res } = await editUser_api(this.form.id, {
            email: this.form.email,
            mobile: this.form.mobile
          })
          if (res.meta.status === 200) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            this.dialogFormVisible2 = !this.dialogFormVisible2
            this.getUsers()
          }
        }
      })

    },
    // 删除用户
    async handleDelete(row) {
      const res2 = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      if (res2 == 'confirm') {
        const { data: res } = await delUser_api(row.id)
        // console.log(res, 123);
        this.getUsers()
      }
    },
    // 更新用户状态
    async changeUserState(row) {
      const { data: res } = await changeUserState_api(row.id, row.mg_state)
      if (res.meta.status === 200) {
        this.$message({
          message: '更新状态成功',
          type: 'success'
        })
      }
    },
    // 分配角色
    // 获取用户信息  用户id，用户名，用户角色名称  获取角色名称
    async setting(row) {
      this.dialogFormVisible3 = true
      this.sname = row.username
      this.srole = row.role_name
      this.uid = row.id
      // console.log(res, 11111111111);
      const { data: res } = await getUserRolenam_api()
      this.rolemsg = res.data
    },
    // 分配角色名称
    async fenpeiRole() {
      const { data: res } = await fenpeiRole_api({ rid: this.form.rid, id: this.uid })
      // console.log(this.rid, this.uid, res, 222333)
      if (res.meta.status == 200) {
        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
        this.dialogFormVisible3 = false
        this.getUsers()
      } else {
        this.$message.error('分配角色失败');
        this.dialogFormVisible3 = false
      }
    },
    // 分页
    handleSizeChange(val) {
      this.userObj.pagesize = val
      this.getUsers()
      // console.log(`每页 ${val} 条`, val, '00000')
    },
    handleCurrentChange(val) {
      this.userObj.pagenum = val
      this.getUsers()
      // console.log(`当前页: ${val}`, val)
    }
  }
}
</script>
<style lang="less" scoped>
.box-card {
  width: 100%;
  margin-top: 20px;
}
.top {
  text-align: center;
}
</style>
